import { defineStore } from "pinia";
import { ref, computed } from "vue";
import { personaApi } from "@/api/services";
import type {
  Persona,
  PersonaCategory,
  CreatePersonaRequest,
  UpdatePersonaRequest,
} from "@/types/persona";

export const usePersonaStore = defineStore(
  "persona",
  () => {
    // 状态
    const personas = ref<Persona[]>([]);
    const categories = ref<PersonaCategory[]>([]);
    const currentPersona = ref<Persona | null>(null);
    const isLoading = ref(false);
    const searchQuery = ref("");
    const selectedCategory = ref<string>("");
    const sortBy = ref<"name" | "createdAt" | "popularity">("name");
    const sortOrder = ref<"asc" | "desc">("asc");
    const pagination = ref({
      page: 1,
      limit: 20,
      total: 0,
      totalPages: 0,
    });

    // 计算属性
    const filteredPersonas = computed(() => {
      let filtered = personas.value;

      // 按分类过滤
      if (selectedCategory.value) {
        filtered = filtered.filter(
          (p) => p.categoryId === selectedCategory.value,
        );
      }

      // 按搜索关键词过滤
      if (searchQuery.value) {
        const query = searchQuery.value.toLowerCase();
        filtered = filtered.filter(
          (p) =>
            p.name.toLowerCase().includes(query) ||
            p.description.toLowerCase().includes(query) ||
            p.tags?.some((tag) => tag.toLowerCase().includes(query)),
        );
      }

      // 排序
      filtered.sort((a, b) => {
        let aValue: any, bValue: any;

        switch (sortBy.value) {
          case "name":
            aValue = a.name.toLowerCase();
            bValue = b.name.toLowerCase();
            break;
          case "createdAt":
            aValue = new Date(a.createdAt).getTime();
            bValue = new Date(b.createdAt).getTime();
            break;
          case "popularity":
            aValue = a.usageCount || 0;
            bValue = b.usageCount || 0;
            break;
          default:
            return 0;
        }

        if (sortOrder.value === "asc") {
          return aValue < bValue ? -1 : aValue > bValue ? 1 : 0;
        } else {
          return aValue > bValue ? -1 : aValue < bValue ? 1 : 0;
        }
      });

      return filtered;
    });

    const popularPersonas = computed(() => {
      return personas.value
        .filter((p) => p.isPublic)
        .sort((a, b) => (b.usageCount || 0) - (a.usageCount || 0))
        .slice(0, 10);
    });

    const myPersonas = computed(() => {
      return personas.value.filter((p) => p.isOwner);
    });

    const publicPersonas = computed(() => {
      return personas.value.filter((p) => p.isPublic && !p.isOwner);
    });

    const favoritePersonas = computed(() => {
      return personas.value.filter((p) => p.isFavorite);
    });

    const hasPersonas = computed(() => {
      return personas.value.length > 0;
    });

    const totalCount = computed(() => {
      return pagination.value.total;
    });

    // 方法
    const loadPersonas = async (params?: {
      page?: number;
      limit?: number;
      category?: string;
      search?: string;
      sortBy?: string;
      sortOrder?: string;
    }) => {
      isLoading.value = true;

      const queryParams = {
        page: params?.page || pagination.value.page,
        limit: params?.limit || pagination.value.limit,
        category: params?.category || selectedCategory.value,
        search: params?.search || searchQuery.value,
        sortBy: params?.sortBy || sortBy.value,
        sortOrder: params?.sortOrder || sortOrder.value,
      };

      const response = await personaApi.getPersonas(queryParams);
      const { data, pagination: paginationData } = response;

      if (queryParams.page === 1) {
        personas.value = data;
      } else {
        // 分页加载，追加数据
        personas.value.push(...data);
      }

      pagination.value = paginationData;
      isLoading.value = false;

      return response;
    };

    const switchPersona = async (personaId: string) => {
      isLoading.value = true;

      // 获取人格详情
      const persona = await getPersonaById(personaId);

      // 设置为当前人格
      currentPersona.value = persona;

      // 保存到本地存储
      localStorage.setItem("currentPersonaId", personaId);

      // 触发人格切换事件
      emitPersonaSwitch(persona);

      isLoading.value = false;
      return persona;
    };

    const loadCurrentPersona = async () => {
      const savedPersonaId = localStorage.getItem("currentPersonaId");
      if (savedPersonaId) {
        const persona = await getPersonaById(savedPersonaId);
        currentPersona.value = persona;
        return persona;
      }
      return null;
    };

    const loadCategories = async () => {
      const response = await personaApi.getCategories();
      categories.value = response;
      return response;
    };

    const getPersonaById = async (id: string) => {
      // 先从本地查找
      const localPersona = personas.value.find((p) => p.id === id);
      if (localPersona) {
        return localPersona;
      }

      // 从服务器获取
      const response = await personaApi.getPersonaById(id);
      const persona = response;

      // 添加到本地列表
      const existingIndex = personas.value.findIndex((p) => p.id === id);
      if (existingIndex !== -1) {
        personas.value[existingIndex] = persona;
      } else {
        personas.value.push(persona);
      }

      return persona;
    };

    const createPersona = async (personaData: CreatePersonaRequest) => {
      isLoading.value = true;
      const response = await personaApi.createPersona(personaData);
      const newPersona = response;

      // 添加到列表开头
      personas.value.unshift(newPersona);
      isLoading.value = false;

      return response;
    };

    const updatePersona = async (id: string, updates: UpdatePersonaRequest) => {
      isLoading.value = true;
      const response = await personaApi.updatePersona(id, updates);
      const updatedPersona = response;

      // 更新本地数据
      const index = personas.value.findIndex((p) => p.id === id);
      if (index !== -1) {
        personas.value[index] = updatedPersona;
      }

      // 如果是当前人格，也更新当前人格
      if (currentPersona.value?.id === id) {
        currentPersona.value = updatedPersona;
      }

      isLoading.value = false;
      return response;
    };

    const deletePersona = async (id: string) => {
      await personaApi.deletePersona(id);

      // 从列表中移除
      const index = personas.value.findIndex((p) => p.id === id);
      if (index !== -1) {
        personas.value.splice(index, 1);
      }

      // 如果删除的是当前人格，清空当前人格
      if (currentPersona.value?.id === id) {
        currentPersona.value = null;
      }
    };

    const clonePersona = async (id: string, name?: string) => {
      isLoading.value = true;
      const response = await personaApi.clonePersona(id, { name });
      const clonedPersona = response;

      // 添加到列表
      personas.value.unshift(clonedPersona);
      isLoading.value = false;

      return response;
    };

    const toggleFavorite = async (id: string) => {
      const persona = personas.value.find((p) => p.id === id);
      if (!persona) return;

      const response = await personaApi.toggleFavorite(id);

      // 更新本地状态
      persona.isFavorite = !persona.isFavorite;

      return response;
    };

    const setCurrentPersona = (persona: Persona | null) => {
      currentPersona.value = persona;
    };

    const searchPersonas = async (query: string) => {
      searchQuery.value = query;
      pagination.value.page = 1;
      await loadPersonas({ search: query, page: 1 });
    };

    const filterByCategory = async (categoryId: string) => {
      selectedCategory.value = categoryId;
      pagination.value.page = 1;
      await loadPersonas({ category: categoryId, page: 1 });
    };

    const setSorting = async (
      field: "name" | "createdAt" | "popularity",
      order: "asc" | "desc",
    ) => {
      sortBy.value = field;
      sortOrder.value = order;
      pagination.value.page = 1;
      await loadPersonas({ sortBy: field, sortOrder: order, page: 1 });
    };

    const loadMore = async () => {
      if (pagination.value.page < pagination.value.totalPages) {
        pagination.value.page++;
        await loadPersonas({ page: pagination.value.page });
      }
    };

    const refresh = async () => {
      pagination.value.page = 1;
      await loadPersonas({ page: 1 });
    };

    const clearFilters = async () => {
      searchQuery.value = "";
      selectedCategory.value = "";
      sortBy.value = "name";
      sortOrder.value = "asc";
      pagination.value.page = 1;
      await loadPersonas({ page: 1 });
    };

    const getPersonaStats = async (id: string) => {
      return await personaApi.getPersonaStats(id);
    };

    const exportPersona = async (
      id: string,
      format: "json" | "yaml" = "json",
    ) => {
      return await personaApi.exportPersona(id, format);
    };

    const importPersona = async (
      data: any,
      format: "json" | "yaml" = "json",
    ) => {
      isLoading.value = true;
      const response = await personaApi.importPersona(data, format);
      const importedPersona = response;

      // 添加到列表
      personas.value.unshift(importedPersona);
      isLoading.value = false;

      return response;
    };

    const validatePersona = async (personaData: Partial<Persona>) => {
      return await personaApi.validatePersona(personaData);
    };

    const getRecommendedPersonas = async (limit = 10) => {
      return await personaApi.getRecommendedPersonas(limit);
    };

    const reportPersona = async (
      id: string,
      reason: string,
      description?: string,
    ) => {
      return await personaApi.reportPersona(id, { reason, description });
    };

    return {
      // 状态
      personas,
      categories,
      currentPersona,
      isLoading,
      searchQuery,
      selectedCategory,
      sortBy,
      sortOrder,
      pagination,

      // 计算属性
      filteredPersonas,
      popularPersonas,
      myPersonas,
      publicPersonas,
      favoritePersonas,
      hasPersonas,
      totalCount,

      // 方法
      loadPersonas,
      loadCategories,
      getPersonaById,
      createPersona,
      updatePersona,
      deletePersona,
      clonePersona,
      toggleFavorite,
      setCurrentPersona,
      switchPersona,
      loadCurrentPersona,
      searchPersonas,
      filterByCategory,
      setSorting,
      loadMore,
      refresh,
      clearFilters,
      getPersonaStats,
      exportPersona,
      importPersona,
      validatePersona,
      getRecommendedPersonas,
      reportPersona,
    };
  },
  {
    persist: {
      key: "persona-store",
      paths: ["currentPersona", "selectedCategory", "sortBy", "sortOrder"],
      storage: localStorage,
    },
  },
);
